package yn.micro.web.advice;

import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.ExceptionUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import yn.micro.common.context.ReqNoContext;
import yn.micro.common.exception.enums.RequestMethodExceptionEnum;
import yn.micro.common.exception.enums.ServerExceptionEnum;
import yn.micro.common.pojo.response.ErrorResponse;

import javax.servlet.http.HttpServletRequest;



/**
 * 全局异常处理器
 *
 */
@Order(1)
@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice {


    /**
     * 拦截请求方法的异常response
     *
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public ErrorResponse methodNotSupport(HttpServletRequest request) {
        if (ServletUtil.isPostMethod(request)) {
            log.error(">>> 请求方法异常，请求号为：{}，具体信息为：{}", ReqNoContext.get(), RequestMethodExceptionEnum.REQUEST_METHOD_IS_GET.getMessage());
            return ErrorResponse.error(RequestMethodExceptionEnum.REQUEST_METHOD_IS_GET.getCode(),
                    RequestMethodExceptionEnum.REQUEST_METHOD_IS_GET.getMessage());
        }
        if (ServletUtil.isGetMethod(request)) {
            log.error(">>> 请求方法异常，请求号为：{}，具体信息为：{}", ReqNoContext.get() ,RequestMethodExceptionEnum.REQUEST_METHOD_IS_POST.getMessage());
            return ErrorResponse.error(RequestMethodExceptionEnum.REQUEST_METHOD_IS_POST.getCode(),
                    RequestMethodExceptionEnum.REQUEST_METHOD_IS_POST.getMessage());
        }
        return null;
    }

    /**
     * 拦截请求方法的异常response
     *
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ErrorResponse exceptionHandler(Exception e) {
            log.error(">>> 请求方法异常，请求号为：{}，具体异常信息为：{}", ReqNoContext.get(), e);
            return ErrorResponse.error(ServerExceptionEnum.SERVER_ERROR.getCode(),
                    ServerExceptionEnum.SERVER_ERROR.getMessage());
    }

}
